<?php

namespace app\admin\logic;

use app\admin\model\Community;
use app\admin\model\Form1;
use app\admin\model\PositiveAlarm;
use app\common\basics\Logic;
use EasyAdmin\upload\Uploadfile;
use jianyan\excel\Excel;
use think\App;
use think\Exception;

/**
 * Form1逻辑层
 */
class Form1Logic extends Logic
{
    /**
     * 导入14日返沙人员信息
     * @param array $post 数据
     * @return bool
     */
    public static function import(array $post)
    {
        try {
            $uploadConfig = sysconfig('upload');
            $upload = Uploadfile::instance()
                ->setUploadType($post['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($post['file'])
                ->save();
            if ($upload['save'] <> true) throw new Exception($upload['msg']);

            $address = parse_url($upload['url']);
            $path = public_path() . trim($address['path'],'/');
            $data = Excel::import($path, 3);
            if (empty($data)) throw new Exception('模板的数据行不能为空');

            $arr = [];
            foreach ($data as $v) {
                $res = [
                    'name'          =>  $v[0],
                    'sex'           =>  trim($v[1]) == '男' ? 0 : 1,
                    'id_card'       =>  $v[2],
                    'mobile'        =>  $v[3],
                    'living'        =>  $v[4],
                    'domicile'      =>  $v[5],
                    'employer'      =>  $v[6],
                    'buy_way'       =>  $v[7],
                    'arrival_time'  =>  $v[8],
                    'departure'     =>  $v[9],
                    'check_time'    =>  $v[10],
                    'check_result'  =>  trim($v[11]) == '阴性' ? 0 : 1,
                    'community'     =>  Community::getNameById($v[12]),
                ];

                if (empty($res['id_card'])) continue;

                if (strtotime($res['arrival_time']) > time()) {
                    continue;
                }
                if (strtotime($res['check_time']) > time()) {
                    continue;
                }
                //阳性报警
                if ($res['check_result'] == 1) {
                    (new PositiveAlarm())->save($res);
                }

                //当有未解除的，还重复提交时，将旧的标注为已废弃
                $old = Form1::where([
                    'id_card' => $res['id_card'],
                    'status'  => 0,
                ])->order('id', 'desc')->limit(1)->find();
                if (!empty($old)) {
                    $old->status = 2;
                    $old->save();
                }

                $arr[] = $res;
            }

            (new Form1())->saveAll($arr);
            return true;
        } catch (\Exception $e) {
            self::$error = $e->getMessage();
            return false;
        }
    }
}